package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.CaseDataStatus;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.StopCaseModel;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.entity.mysql.QCaseInfo;
import cn.fintecher.pangolin.service.dataimp.model.ConfirmCommonModel;
import cn.fintecher.pangolin.service.dataimp.repository.CaseInfoRepository;
import org.apache.commons.collections4.IterableUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:17 2019/11/5
 */

@Service("confirmStopFuture")
public class ConfirmStopFuture {
    @Autowired
    private CaseInfoRepository caseInfoRepository;

    /**
     * 多线程确认
     */
    @Async
    public CompletableFuture<List<CaseInfo>> processStop(List<StopCaseModel> list) {
        List<CaseInfo> caseInfos = new ArrayList<>();
        List<String> caseNumbers = new ArrayList<>();
        for (StopCaseModel stopCaseModel : list) {
            caseNumbers.add(stopCaseModel.getCaseNumber());
        }
        Iterable<CaseInfo> iterable = caseInfoRepository.findAll(QCaseInfo.caseInfo.caseNumber.in(caseNumbers));
        List<CaseInfo> caseInfoList = IterableUtils.toList(iterable);
        Map<String, ConfirmCommonModel> map = new HashMap<>();
        for (StopCaseModel stopCaseModel : list) {
            ConfirmCommonModel confirmCommonModel = new ConfirmCommonModel();
            for (CaseInfo caseInfo : caseInfoList) {
                if (stopCaseModel.getCaseNumber().equals(caseInfo.getCaseNumber())) {
                    confirmCommonModel.setCaseInfo(caseInfo);
                    break;
                }
            }
            map.put(stopCaseModel.getCaseNumber(), confirmCommonModel);
        }
        for (Map.Entry<String, ConfirmCommonModel> entry : map.entrySet()) {
            ConfirmCommonModel confirmCommonModel = entry.getValue();
            CaseInfo caseInfo = confirmCommonModel.getCaseInfo();
            if (Objects.nonNull(caseInfo)) {
                caseInfo.setCaseDataStatus(CaseDataStatus.PAUSE); //停催
                caseInfo.setStopTime(ZWDateUtil.getNowDateTime()); //停催时间
                caseInfos.add(caseInfo);
            }
        }
        return CompletableFuture.completedFuture(caseInfos);
    }
}
